package thinkinginjava.concurrency;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;


public class PrimeGenerator implements Runnable{
	private final List<BigInteger> primes = new ArrayList<BigInteger>();
	private boolean cancelled;
	@Override
	public void run() {
		BigInteger p = BigInteger.ONE;
		while(!cancelled) {
			p = p.nextProbablePrime();
			synchronized (this) {
				primes.add(p);	
			}
		}
	}

	public void cancel() {
		this.cancelled = true;
	}
	
	public synchronized List<BigInteger> getPrimes() {
		return new ArrayList<BigInteger>(this.primes);
	}
	
	public static void main(String[] args) throws InterruptedException {
		PrimeGenerator g = new PrimeGenerator();
		new Thread(g).start();
		
		try {
			Thread.sleep(3 * 1000);
		} finally {
			g.cancel();
		}
		
		System.out.println(g.getPrimes());
	}
}
